package com.yunkuhui.www.demo.exceptionhandler;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @ RestControllerAdvice 的范围有：
 * ①basePackages：应用在xx包
 * ②basePackageClasses：应用在xx类
 * ③assignableTypes：应用在加了@Controller的类
 * ④annotations：应用在带有xx注解的类或者方法
 */
@RestControllerAdvice
public class SystemExceptionHandler {

	private final static Logger logger = LoggerFactory.getLogger(SystemExceptionHandler.class);

	@ExceptionHandler(value = {IOException.class, NullPointerException.class})
	public Object ioExceptionHandler(HttpServletRequest req, HttpServletResponse res, Exception e) {
		logger.debug("uri: " + req.getRequestURI());
		logger.debug("status: " + res.getStatus());
		logger.debug("关流失败", e);
		e.printStackTrace();
		return e;
	}

	@ExceptionHandler(value = Exception.class)
	public Map<String, String> defaultErrorHandler(HttpServletRequest req, HttpServletResponse res, Exception e) {
		logger.debug("uri: " + req.getRequestURI());
		logger.debug("status: " + res.getStatus());
		logger.debug("系统级别错误", e);
		System.out.println("Exception");
		e.printStackTrace();
		Map<String, String> errorMap = new HashMap<>();
		errorMap.put("resultCode", "01");
		errorMap.put("errorCode", "");
		errorMap.put("errorMessage", "服务器错误");
		return errorMap;
	}
}
